package com.ssy.lingxi.member.merchant.serviceimpl.mobile;

import cn.hutool.core.util.ObjectUtil;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.constant.member.RoleTypeEnum;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberSalesFindUserIdVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberSalesReportOrderCountFeignVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberSalesChannelCountQueryVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberSalesFeignPageQueryVO;
import com.ssy.lingxi.member.merchant.entity.*;
import com.ssy.lingxi.member.merchant.model.vo.basic.response.MemberUserChannelVO;
import com.ssy.lingxi.member.merchant.model.vo.basic.response.MobileMemberSalesInformationVO;
import com.ssy.lingxi.member.merchant.repository.MemberUserChannelRepository;
import com.ssy.lingxi.member.merchant.repository.MemberUserRepository;
import com.ssy.lingxi.member.merchant.service.base.IBaseMemberCacheService;
import com.ssy.lingxi.member.merchant.service.mobile.IMobileMemberSalesService;
import com.ssy.lingxi.member.merchant.utils.MemberOrganizationUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 业务员小程序--订单服务远程调用-业绩统计需要的会员信息-相关的接口
 *
 * @author 郑小翠
 * @version 2.02.18
 * @date 2022-03-24
 */
@Service
public class MobileMemberSalesServiceImpl implements IMobileMemberSalesService {

    @Resource
    private IBaseMemberCacheService memberCacheService;

    @Resource
    private MemberUserRepository memberUserRepository;

    @Resource
    private JPAQueryFactory jpaQueryFactory;

    /**
     * 查看业务员详情
     *
     * @param headers 头部信息
     * @return 操作接口
     */
    @Override
    public Wrapper<MobileMemberSalesInformationVO> getSalesInformation(HttpHeaders headers) {
        UserLoginCacheDTO loginCacheDTO = memberCacheService.needLoginFromMobile(headers);
        MemberUserDO userDO = memberUserRepository.findById(loginCacheDTO.getUserId()).orElse(null);

        if (ObjectUtil.isNull(userDO)) {
            return Wrapper.success();
        }
        List<MemberOrganizationDO> orgList = new ArrayList<>(userDO.getMember().getOrgs());
        MobileMemberSalesInformationVO queryVO = new MobileMemberSalesInformationVO();
        queryVO.setUserId(userDO.getId());
        queryVO.setName(userDO.getName());
        queryVO.setAccount(userDO.getAccount());
        queryVO.setRoleName(userDO.getRoles().stream().map(MemberRoleDO::getRoleName).collect(Collectors.joining(",")));
        queryVO.setTitle(MemberOrganizationUtil.joinTitleToString(userDO.getOrg() == null ? 0L : userDO.getOrg().getId(), orgList));
        return Wrapper.success(queryVO);
    }

    /**
     * 远程调用--查看业务员统计
     *
     * @param pageVO 查询条件
     * @return 返回下级会员信息
     */
    @Override
    public Wrapper<PageData<MemberSalesFeignPageQueryVO>> getSalesList(MemberSalesFindUserIdVO pageVO) {
        MemberUserDO userDO = memberUserRepository.findById(pageVO.getUserId()).orElse(null);
        if (userDO == null || userDO.getMember() == null || !userDO.getMember().getId().equals(pageVO.getMemberId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_USER_DOES_NOT_EXIST);
        }

        if (userDO.getIsSales() == null || userDO.getIsSales().equals(EnableDisableStatus.DISABLE.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_USER_IS_NOT_SALES);
        }

        // 找到全部的下级会员
        List<MemberUserChannelDO> channels = userDO.getUserAuth().getChannels().stream().filter(channel -> channel.getRoleId().equals(pageVO.getMemberRoleId())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(channels)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        // 关系Id
        List<Long> relationIds = channels.stream().map(MemberUserChannelDO::getMemberRelationId).collect(Collectors.toList());

        // 根据关系Id结合用户输入查询条件 找到所有的下级会员并返回VO对象
        if (ObjectUtil.isNotNull(relationIds)) {

            QMemberUserChannelDO qMemberUserChannelDO = QMemberUserChannelDO.memberUserChannelDO;
            QMemberRelationDO qMemberRelationDO = QMemberRelationDO.memberRelationDO;
            QMemberUserDO qMemberUserDO = QMemberUserDO.memberUserDO;
            QRoleDO qRoleDO = QRoleDO.roleDO;
            QRoleTypeDO qRoleTypeDO = QRoleTypeDO.roleTypeDO;
            JPAQuery<MemberSalesFeignPageQueryVO> query =
                    jpaQueryFactory.select(Projections.constructor(MemberSalesFeignPageQueryVO.class, qMemberUserChannelDO.memberRelationId,qMemberUserChannelDO.subMemberId, qMemberRelationDO.subMember.name, qMemberRelationDO.subRoleId, qMemberRelationDO.subRole.roleName))
                            .from(qMemberUserChannelDO)
                            .leftJoin(qMemberUserDO).on(qMemberUserChannelDO.userId.eq(qMemberUserDO.id))
                            .leftJoin(qMemberRelationDO).on(qMemberUserChannelDO.memberRelationId.eq(qMemberRelationDO.id))
                            .leftJoin(qRoleDO).on(qMemberRelationDO.subRoleId.eq(qRoleDO.id))
                            .leftJoin(qRoleTypeDO).on(qRoleDO.roleType.eq(qRoleTypeDO))
                            .where(qRoleTypeDO.typeEnum.eq(RoleTypeEnum.SERVICE_CONSUMER.getCode()))
                            .where(qMemberUserChannelDO.userId.eq(pageVO.getUserId()))
                            .where(qMemberRelationDO.id.in(relationIds))
                            .groupBy(qMemberUserChannelDO.memberRelationId,qMemberUserChannelDO.subMemberId, qMemberRelationDO.subMember.name, qMemberRelationDO.subRoleId, qMemberRelationDO.subRole.roleName);

            if (StringUtils.hasLength(pageVO.getMemberName())) {
                query.where(qMemberRelationDO.subMember.name.eq(pageVO.getMemberName()));
            }
            if (ObjectUtil.isNotNull(pageVO.getCurrent()) && ObjectUtil.isNotNull(pageVO.getPageSize())) {
                query.limit(pageVO.getPageSize()).offset((long) (pageVO.getCurrent() - 1) * pageVO.getPageSize());
            }
            //总数
            long totalCount = query.fetch().size();

            // 所有下级会员信息
            List<MemberSalesFeignPageQueryVO> result = query.orderBy(qMemberUserChannelDO.memberRelationId.desc()).fetch();
            return Wrapper.success(new PageData<>(totalCount, result));
        }

        return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
    }

}
